package com.hxh.generater.vue;

import com.hxh.entity.Project;
import com.hxh.entity.TemplateConfig;
import com.hxh.entity.po.ClassInfo;
import com.hxh.service.TemplateConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 通过读取模板, 自动生成代码的类，屏蔽不同模板之间的差异，统一调用
 * 生成vue代码的转接口
 */
@Slf4j
@Component
public class GenerationVueAdapter {

    private static final String GENERATION_VIEW_METHOD = "generationView";
    private static final String GENERATION_API_METHOD = "generationApi";
    private static final String INIT_CORE_METHOD = "initCore";

    @Autowired
    TemplateConfigService templateConfigService;

    /**
     * 根据配置，在项目中生成view代码文件
     *
     * @param project
     * @param classInfo
     * @throws Exception
     */
    public void generationView(Project project, ClassInfo classInfo) throws Exception {
        String template = project.getTemplate();
        TemplateConfig myTemplate = templateConfigService.getTemplateConfigByName(template);
        Class<?> vueClass = Class.forName(myTemplate.getGenVue());
        Object vueObject = vueClass.newInstance();
        Method generationViewMethod = vueObject.getClass().getDeclaredMethod(GENERATION_VIEW_METHOD, Project.class, ClassInfo.class);
        generationViewMethod.invoke(vueObject, project, classInfo);
    }

    /**
     * 在项目中生成api的js代码文件
     *
     * @param project
     * @param classInfo
     * @throws Exception
     */
    public void generationApi(Project project, ClassInfo classInfo) throws Exception {
        String template = project.getTemplate();
        TemplateConfig myTemplate = templateConfigService.getTemplateConfigByName(template);
        Class<?> vueClass = Class.forName(myTemplate.getGenVue());
        Object vueObject = vueClass.newInstance();
        Method generationApiMethod = vueObject.getClass().getDeclaredMethod(GENERATION_API_METHOD, Project.class, ClassInfo.class);
        generationApiMethod.invoke(vueObject, project, classInfo);
    }

    /**
     * 初始化项目
     * @param project
     * @param initExtendTable 初始化除了模板内置表的页面外，是否要初始化用户自己创建表的页面
     * @throws Exception
     */
    public void initProject(Project project, boolean initExtendTable) throws Exception {
        String template = project.getTemplate();
        TemplateConfig myTemplate = templateConfigService.getTemplateConfigByName(template);
        Class<?> initVueProjectClass = Class.forName(myTemplate.getInitVueProject());
        Object initVueProjectObject = initVueProjectClass.newInstance();
        Method initCoreMethod = initVueProjectObject.getClass().getSuperclass().getDeclaredMethod(INIT_CORE_METHOD, Project.class, Boolean.class);
        initCoreMethod.invoke(initVueProjectObject, project, initExtendTable);
    }

}
